#include "dataView.h"
#include <QHeaderView>

DataView::DataView(QWidget *parent) : 
QWidget(parent)
{
    QWidget *topWidget = new QWidget(this);
    QHBoxLayout *hlayout = new QHBoxLayout(this);
    QLabel *label_choose = new QLabel("选择", this);
    QLabel *label_seq = new QLabel("序号", this);
    QLabel *label_link = new QLabel("连接状态", this);
    QLabel *label_pos = new QLabel("位置", this);
    QLabel *label_state = new QLabel("状态", this);
    label_state->setFixedHeight(40);
    hlayout->addWidget(label_choose);
    hlayout->addWidget(label_seq);
    hlayout->addWidget(label_link);
    hlayout->addWidget(label_pos);
    hlayout->addWidget(label_state);
        // Set the stretch factors
    hlayout->setStretch(0, 1);  // checkBox
    hlayout->setStretch(1, 1);  // sequenceLabel
    hlayout->setStretch(2, 2);  // connectionStateLabel
    hlayout->setStretch(3, 4);  // locationInfoLabel
    hlayout->setStretch(4, 2);  // statusInfoLabel
    topWidget->setLayout(hlayout);
    topWidget->setFixedHeight(40);  // 设置固定高度为40像素

    tableWidget = new QTableWidget(this);
    tableWidget->setColumnCount(1); // 单列垂直布局
    tableWidget->horizontalHeader()->setStretchLastSection(true);  // 使最后一列（即唯一的一列）填满
    tableWidget->horizontalHeader()->setSectionResizeMode(QHeaderView::Stretch);
    // tableWidget->setFixedHeight(40);
    tableWidget->setRowCount(0); // 初始没有行
    // tableWidget->insertRow(0);
    // DataItem *dataItem = new DataItem(1,1,this);
    // dataItem->setFixedHeight(50);
    // tableWidget->setCellWidget(0, 0, dataItem);

    // tableWidget->setSizePolicy(QSizePolicy::Expanding, QSizePolicy::Expanding);
    // vlayout->addWidget(new QLabel("test", this));


    QVBoxLayout *layout = new QVBoxLayout(this);
    layout->addWidget(topWidget);
    layout->addWidget(tableWidget);
    layout->setStretch(0,0);
    layout->setStretch(1,1);

    setLayout(layout);
}

void DataView::updateData(const QList<DataItem> &dataItems)
{
    // tableWidget->setRowCount(dataItems.size());

    // for (int row = 0; row < dataItems.size(); ++row) {
    //     const DataItem &item = dataItems[row];

    //     QTableWidgetItem *checkItem = new QTableWidgetItem();
    //     checkItem->setCheckState(item.selected ? Qt::Checked : Qt::Unchecked);
    //     tableWidget->setItem(row, 0, checkItem);

    //     QTableWidgetItem *indexItem = new QTableWidgetItem(QString::number(item.index));
    //     tableWidget->setItem(row, 1, indexItem);

    //     QTableWidgetItem *connectionStatusItem = new QTableWidgetItem(item.connectionStatus);
    //     tableWidget->setItem(row, 2, connectionStatusItem);

    //     QTableWidgetItem *dataItem = new QTableWidgetItem(item.data);
    //     tableWidget->setItem(row, 3, dataItem);

    //     QTableWidgetItem *noteItem = new QTableWidgetItem(item.note);
    //     tableWidget->setItem(row, 4, noteItem);
    // }
}

void DataView::receiveMsgSlot(const mavlink_message_t& message) {
    switch (message.msgid) {
        case MAVLINK_MSG_ID_MISSION_CMD_ACK: {
            
            mavlink_mission_cmd_ack_t mission_cmd_ack;
            mavlink_msg_mission_cmd_ack_decode(&message, &mission_cmd_ack);
            std::cout<<"tcp get MAVLINK_MSG_ID_MISSION_CMD_ACK:"<<mission_cmd_ack.drone_id<<std::endl;
            break;
        }
        case MAVLINK_MSG_ID_MISSION_HEARTBEAT_1HZ: {
            mavlink_mission_heartbeat_1hz_t mission_hb_1hz;
            mavlink_msg_mission_heartbeat_1hz_decode(&message, &mission_hb_1hz);
            std::cout<<"tcp get MAVLINK_MSG_ID_MISSION_HEARTBEAT_1HZ:"<<mission_hb_1hz.drone_id<<std::endl;
            if(updateHB(mission_hb_1hz) < 0) {
                addNewTableUav(mission_hb_1hz);
            }
            break;
        }
        case MAVLINK_MSG_ID_MISSION_HEARTBEAT_5HZ: {
            mavlink_mission_heartbeat_5hz_t mission_hb_5hz;
            mavlink_msg_mission_heartbeat_5hz_decode(&message, &mission_hb_5hz);
            std::cout<<"tcp get MAVLINK_MSG_ID_MISSION_HEARTBEAT_5HZ:"<<mission_hb_5hz.drone_id<<std::endl;
            if(updateHB(mission_hb_5hz) < 0) {
                addNewTableUav(mission_hb_5hz);
            }
            break;
        }
        default:
            break;
        
    }
}

int DataView::updateHB(const mavlink_mission_heartbeat_1hz_t &msg){
    int ret = -1;
    for (int i = 0; i < tableWidget->rowCount(); ++i) {
        DataItem *dataItem = static_cast<DataItem *>(tableWidget->cellWidget(i, 0));
        if (msg.drone_id == dataItem->getDroneId() &&
            msg.drone_type == dataItem->getDroneType()) {
            MissionHeartbeat1hz_t h1_msg;
            h1_msg.seq = msg.seq;
            h1_msg.drone_type = msg.drone_type;
            h1_msg.drone_id = msg.drone_id;
            h1_msg.fcs_flight_mode = msg.fcs_flight_mode;
            h1_msg.fcs_arm = msg.fcs_arm;
            h1_msg.smart_mode = msg.smart_mode;
            h1_msg.smart_mode_status = msg.smart_mode_status;
            h1_msg.is_home_invalid = msg.is_home_invalid;
            h1_msg.home_x_lat = msg.home_x_lat * 1e-7;
            h1_msg.home_y_lon = msg.home_y_lon * 1e-7;
            h1_msg.home_z_alt = msg.home_z_alt * 1e-3;
            h1_msg.backup_home_lat = msg.backup_home_lat * 1e-7;
            h1_msg.backup_home_lon = msg.backup_home_lon * 1e-7;
            h1_msg.backup_home_alt = msg.backup_home_alt * 1e-3;
            h1_msg.backup_home_valid = msg.backup_home_valid;
            dataItem->update(h1_msg);
            ret = msg.drone_id;
            break;
        }
    }
    return ret;
}
int DataView::updateHB(const mavlink_mission_heartbeat_5hz_t &msg){
    int ret = -1;
    for (int i = 0; i < tableWidget->rowCount(); ++i) {
        DataItem *dataItem = static_cast<DataItem *>(tableWidget->cellWidget(i, 0));
        if (msg.drone_id == dataItem->getDroneId() &&
            msg.drone_type == dataItem->getDroneType()) {
            MissionHeartbeat5hz_t h5_msg;
            h5_msg.seq = msg.seq;
            h5_msg.drone_type = msg.drone_type;
            h5_msg.drone_id = msg.drone_id;
            h5_msg.is_gps_invalid = msg.is_gps_invalid;
            h5_msg.uav_lat = msg.uav_lat * 1e-7;
            h5_msg.uav_lon = msg.uav_lon * 1e-7;
            h5_msg.uav_alt = msg.uav_alt * 1e-3;
            h5_msg.gps_num = msg.gps_num;
            h5_msg.gps_fix = msg.gps_fix;
            h5_msg.roll = msg.roll * 1e-2;
            h5_msg.pitch = msg.pitch * 1e-2;
            h5_msg.yaw = msg.yaw * 1e-2;
            h5_msg.position[0] = msg.pos_x * 1e-3;
            h5_msg.position[1] = msg.pos_y * 1e-3;
            h5_msg.position[2] = msg.pos_z * 1e-3;
            h5_msg.velocity[0] = msg.vel_x * 1e-3;
            h5_msg.velocity[1] = msg.vel_y * 1e-3;
            h5_msg.velocity[2] = msg.vel_z * 1e-3;
            h5_msg.distance_m = msg.distance_mm * 1e-3;
            std::cout<<"pos_z:"<<h5_msg.position[2]<<std::endl;
            dataItem->update(h5_msg);
            ret = msg.drone_id;
            break;
        }
    }
    return ret;
}

void DataView::addNewTableUav(const mavlink_mission_heartbeat_1hz_t &msg) {
    MissionHeartbeat1hz_t h1_msg;
    h1_msg.seq = msg.seq;
    h1_msg.drone_type = msg.drone_type;
    h1_msg.drone_id = msg.drone_id;
    h1_msg.fcs_flight_mode = msg.fcs_flight_mode;
    h1_msg.fcs_arm = msg.fcs_arm;
    h1_msg.smart_mode = msg.smart_mode;
    h1_msg.smart_mode_status = msg.smart_mode_status;
    h1_msg.is_home_invalid = msg.is_home_invalid;
    h1_msg.home_x_lat = msg.home_x_lat * 1e-7;
    h1_msg.home_y_lon = msg.home_y_lon * 1e-7;
    h1_msg.home_z_alt = msg.home_z_alt * 1e-3;
    h1_msg.backup_home_lat = msg.backup_home_lat * 1e-7;
    h1_msg.backup_home_lon = msg.backup_home_lon * 1e-7;
    h1_msg.backup_home_alt = msg.backup_home_alt * 1e-3;
    h1_msg.backup_home_valid = msg.backup_home_valid;

    DataItem *dataItem = new DataItem(h1_msg.drone_type, h1_msg.drone_id, h1_msg, this);
    int row = tableWidget->rowCount();
    tableWidget->insertRow(row);
    tableWidget->setCellWidget(row, 0, dataItem);
}
void DataView::addNewTableUav(const mavlink_mission_heartbeat_5hz_t &msg) {
    MissionHeartbeat5hz_t h5_msg;
    h5_msg.seq = msg.seq;
    h5_msg.drone_type = msg.drone_type;
    h5_msg.drone_id = msg.drone_id;
    h5_msg.is_gps_invalid = msg.is_gps_invalid;
    h5_msg.uav_lat = msg.uav_lat * 1e-7;
    h5_msg.uav_lon = msg.uav_lon * 1e-7;
    h5_msg.uav_alt = msg.uav_alt * 1e-3;
    h5_msg.gps_num = msg.gps_num;
    h5_msg.gps_fix = msg.gps_fix;
    h5_msg.roll = msg.roll * 1e-2;
    h5_msg.pitch = msg.pitch * 1e-2;
    h5_msg.yaw = msg.yaw * 1e-2;
    h5_msg.position[0] = msg.pos_x * 1e-3;
    h5_msg.position[1] = msg.pos_y * 1e-3;
    h5_msg.position[2] = msg.pos_z * 1e-3;
    h5_msg.velocity[0] = msg.vel_x * 1e-3;
    h5_msg.velocity[1] = msg.vel_y * 1e-3;
    h5_msg.velocity[2] = msg.vel_z * 1e-3;
    h5_msg.distance_m = msg.distance_mm * 1e-3;

    DataItem *dataItem = new DataItem(h5_msg.drone_type, h5_msg.drone_id, h5_msg, this);
    int row = tableWidget->rowCount();
    tableWidget->insertRow(row);
    tableWidget->setCellWidget(row, 0, dataItem);
}

////////////////////////////////////////////////////
DataItem::DataItem( const int drone_type, const int drone_id,const MissionHeartbeat5hz_t data,  QWidget *parent)
        : QWidget(parent),
        drone_type_(drone_type),
        drone_id_(drone_id)
    {
        // Create and set up layout
        data_.heartbeat5hz = data;
        initView();
    }
DataItem::DataItem( const int drone_type, const int drone_id,const MissionHeartbeat1hz_t data,  QWidget *parent)
        : QWidget(parent),
        drone_type_(drone_type),
        drone_id_(drone_id)
    {
        // Create and set up layout
        data_.heartbeat1hz = data;
        initView();
    }

void DataItem::initView() {
    QHBoxLayout *layout = new QHBoxLayout(this);
    
    checkBox_ = new QCheckBox();
    checkBox_->setChecked(true);  // 默认勾选

    sequenceLabel_ = new QLabel(QString::number(drone_id_));
    connectionStateLabel_= new QLabel("连接成功");
    locationInfoLabel_ = new QLabel(getPosStr());
    statusInfoLabel_ = new QLabel(getStatusStr());

    // Add widgets to the layout
    layout->addWidget(checkBox_);
    layout->addWidget(sequenceLabel_);
    layout->addWidget(connectionStateLabel_);
    layout->addWidget(locationInfoLabel_);
    layout->addWidget(statusInfoLabel_);
    layout->setStretch(0, 1);  // checkBox
    layout->setStretch(1, 1);  // sequenceLabel
    layout->setStretch(2, 2);  // connectionStateLabel
    layout->setStretch(3, 4);  // locationInfoLabel
    layout->setStretch(4, 2);  // statusInfoLabel

    this->setLayout(layout);
    setFixedHeight(40);
}

void DataItem::update(const MissionHeartbeat1hz_t &msg) {
    {
        std::lock_guard<std::mutex> lock(data_mtx_);
        data_.heartbeat1hz = msg;
    }
    updateView();
}
void DataItem::update(const MissionHeartbeat5hz_t &msg) {
    {
        std::lock_guard<std::mutex> lock(data_mtx_);
        data_.heartbeat5hz = msg;
    }
    updateView();
}

void DataItem::updateView() {
    locationInfoLabel_->setText(getPosStr());   
    statusInfoLabel_->setText(getStatusStr());
}
bool DataItem::isChecked() {
    return checkBox_->isChecked();
}

int DataItem::getDroneType() {
    return drone_type_;
}

int DataItem::getDroneId() {
    return drone_id_;
}

QString DataItem::getPosStr() {
    std::lock_guard<std::mutex> lock(data_mtx_);
    QString ps_str = "x:" + QString::number(data_.heartbeat5hz.position[0]) + 
                    " y:" + QString::number(data_.heartbeat5hz.position[1]) + 
                    " z:" + QString::number(data_.heartbeat5hz.position[2]) +
                    " dis:" + QString::number(data_.heartbeat5hz.distance_m);
    std::cout<<ps_str.toStdString()<<std::endl;
    return ps_str;
}
QString DataItem::getStatusStr() {
    std::lock_guard<std::mutex> lock(data_mtx_);
    QString state_ptr = "arm:" + QString::number(data_.heartbeat1hz.fcs_arm) + 
                        " mode:" + QString::number(data_.heartbeat1hz.fcs_flight_mode);
    std::cout<<state_ptr.toStdString()<<std::endl;
    return state_ptr;
}